#!/bin/bash

if [ -z "$1" ] || [ ! -e "$1" ] || [ -z "$2" ] || [ ! -e "$2" ]; then
    echo "Usages: $0 <working_dir> <repo_diff_file>";
    exit 0;
fi

tmp_key="tmp_splits_"`date +%s`

cat $2 | csplit -qf '' -b $tmp_key".%d.diff" - '/^project.*\/$/' '{*}'

working_dir=`pwd`

for proj_diff in `ls $tmp_key.*.diff`
do 
    chg_dir="$1/"`cat $proj_diff | grep '^project.*\/$' | cut -d " " -f 2`
    echo "Now Patching: $chg_dir"
    if [ -e $chg_dir ]; then
        ( cd $chg_dir; \
            cat $working_dir/$proj_diff | grep -v '^project.*\/$' | patch -Np1;);
    else
        echo "$0: Project directory $chg_dir don't exists.";
    fi
done

rm -fr $tmp_key*
